#!/usr/bin/python
# -*- coding: utf-8 -*-
from urlparse import urlparse
import cmd
import cookielib
import os.path
import re
import threading
import time
import urllib
import urllib2

#-------------------------------------------------
#Create At: 2008-11-5 下午10:12:05 
#Create By: Fla.sam
#
#DESC: HDChina Seed downloader
#
#-------------------------------------------------



class HDCBadRequestError( Exception ):
    pass

class HDCBadSearchTypeError( Exception ):
    pass

class HDCBadInstancesError( Exception ):
    pass

class HDCWebHandle:
    def __init__(self, username, password, auto_login=False, keep_login=False ):
        
        self.username = username
        self.password = password
        self.auto_login = auto_login
        self.keep_login = keep_login
        
        self.USER_AGENT = 'Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'
        self.my_user_agent = [( 'User-Agent', self.USER_AGENT ), ]
        
        self.LOGIN_URL = 'http://hdchina.org/takelogin.php'
        self.LOGOUT_URL = ''
        
        # make my cookie
        self.cj = cookielib.CookieJar()
        self.opener = urllib2.build_opener( urllib2.HTTPCookieProcessor( self.cj ) )
        
        # now add user-agent to request header
        self.opener.addheaders = self.my_user_agent

        # install my user-defined opener to urllib2
        urllib2.install_opener( self.opener )
        
    def request( self, url, **request_param ):
        
        if not hasattr( self, 'opener' ):
            raise HDCBadRequestError
        _request = urllib2.Request( url, urllib.urlencode( request_param ) )
        try:
            res = urllib2.urlopen( _request )
        except urllib2.URLError:
            return 'Error'
        context = res.read()
        res.close()
        return context
        
    def doLogin( self ):
        '''
        登陆虾米网站
        '''
        res = self.request( self.LOGIN_URL, \
                              username=self.username, \
                              password=self.password, \
                              submit='登录' )
        return res
    
    def doDownloadSeed(self, seed_url):
        
        seed_file_name = os.path.basename(urlparse(seed_url)[2])
        print 'Seed will be save at: ',  seed_file_name
        fp = open(seed_file_name,'wb')
        try:
            res = self.request(seed_url)
        except ValueError:
            res = ''
            fp.close()
            raise HDCBadRequestError, 'Http request error...'
        fp.write(res)
        fp.close()
        return True
        
class HDCSDConsole(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = 'HDC#'
        self.intro = u'''Welcome to Fla.sam's HdChina Seed downloader... V0.1
    注意: 请先查看帮助 #help
          在下载种子之前请使用自己的HDC帐号登录 #login your_username your_password
--------------------------------------------------------------------------------
        '''
        
        
        self.hdc_handle = None
        self.hdc_is_logined = False
        
    def do_exit(self, args):
        """Exits from the console"""
        return -1
    
    def do_login(self, args):
        '''
        Login HDC with your username and password
        @param args: username password
        @example:
            #login (username) (password)
            #login your_username your_password
        '''
        try:
            hdc_username, hdc_passwd = args.split()
        except ValueError:
            print 'Input param error'
            return False
        print 'Try to login HDC with Username:%s | Passwd:*****' % hdc_username
        if self.hdc_is_logined:
            pass
        else:
            self.hdc_handle = HDCWebHandle(hdc_username, hdc_passwd)
            self.hdc_handle.doLogin()
            self.hdc_is_logined = True
    
    def do_download(self, args):
        '''
        Download seed from URL
        @param args: url
        @example:
            #download (seed_url)
            #download http://blah_blah
        '''
        print 'Try download seed: ', args
        if self.hdc_is_logined:
            try:
                self.hdc_handle.doDownloadSeed(args)
            except HDCBadRequestError:
                print 'Download seed failed...'
            else:
                print 'Download seed success....'
        else:
            print 'Please login HDChina...'
            
    def emptyline(self):    
        """Do nothing on empty input line"""
        pass

def main():
    #hdc_handle = HDCWebHandle('fla', 'xxxxx')
    #hdc_handle.doLogin()
    
    #print hdc_handle.doDownloadSeed('http://hdchina.org/download.php/7366/bd-gs.hdc.torrent')
    
    command_handle = HDCSDConsole()
    command_handle.cmdloop()

if __name__ == '__main__':
    main()
        